package com.ruoyi.shop.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.shop.config.ShopParameters;
import com.ruoyi.shop.domain.TransLog;
import com.ruoyi.shop.mapper.TransLogMapper;
import com.ruoyi.shop.service.ITransLogService;
import com.ruoyi.web.domain.Member;
import com.ruoyi.web.mapper.MemberMapper;
import com.ruoyi.web.service.IMemberService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2021-11-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TransLogServiceImpl implements ITransLogService {
    private final TransLogMapper transLogMapper;

    private final MemberMapper memberMapper;

    private final MessageServiceImpl messageService;

    private final IMemberService memberService;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public TransLog selectTransLogById(Long id) {
        return transLogMapper.selectTransLogById(id);
    }

    /**
     * 查询未完成订单列表
     *
     * @param transLog 订单
     * @return 订单
     */
    @Override
    public List<TransLog> selectTransLogList(TransLog transLog) {
        return transLogMapper.doingOrders(transLog);
    }

    /**
     * 已完成订单信息
     *
     * @param transLog 订单
     * @return 结果
     */
    @Override
    public List<TransLog> selectDealList(TransLog transLog) {
        List<TransLog> transLogs = transLogMapper.dealOrders(transLog);
        if (CollectionUtil.isNotEmpty(transLogs)) {
            for (TransLog transLog1 : transLogs) {
                String orderStatus = transLog1.getOrderStatus();
                transLog1.setOrderStatus("3".equals(orderStatus) ? "送洗结束"
                        : "4".equals(orderStatus) ? "可取走" : "已取走");
            }
        }

        return transLogs;
    }

    /**
     * 新增订单
     *
     * @param transLog 订单
     * @return 结果
     */
    @Override
    public int insertTransLog(TransLog transLog) {
        int row = 0;
        transLog.setCreateTime(DateUtils.getNowDate());
        try {
            //处理客户信息
            //设置关联客户id
            String phoneNo = transLog.getPhoneNum();
            Member member = memberMapper.selectMemberByPhone(phoneNo);
            if (member == null) {
                log.info("未查询到存在的客户信息，先创建客户信息:");
                Long id = memberMapper.getId();
                member = new Member();
                member.setID(id);
                member.setCHANNEL("1");
                member.setPHONE(phoneNo);
                member.setNAME(transLog.getMemberName());
                member.setRegestTime(new Date());
                memberService.insertMember(member);
            }
            //客户信息处理结束，开始写入交易信息
            transLog.setMemberId(member.getID());
            //自动生成订单号
            String orderNo = getOrderNo();
            transLog.setOrderNo(orderNo);
            //默认为已收取
            if (StringUtils.isEmpty(transLog.getOrderStatus())) {
                transLog.setOrderStatus("1");
            }
            log.info("开始写入交易记录");
            //写入交易记录
            row = transLogMapper.insertTransLog(transLog);
            log.info("写入交易记录结束");
            if (row != 0) {
                log.info("写入交易记录成功，开始处理客户信息：");
                String amount = member.getAMOUNT();
                if(StrUtil.isEmpty(amount)){
                    amount = transLog.getOrderAmount();
                }else {
                    BigDecimal amt = new BigDecimal(amount);
                    amt = amt.add(new BigDecimal(transLog.getOrderAmount()));
                    amount = amt.toString();
                }
                member.setAMOUNT(amount);
                memberService.updateMember(member);
            }
        } catch (Exception e) {
            throw new RuntimeException("添加客户失败，请重试");
        }
        return row;
    }

    /**
     * 修改订单
     *
     * @param transLog 订单
     * @return 结果
     */
    @Override
    public int updateTransLog(TransLog transLog) {
        transLog.setUpdateTime(DateUtils.getNowDate());
        //状态修改为5-已取走则给客户发送短信
        String takeAway = "5";
        if (takeAway.equals(transLog.getOrderStatus())) {
            messageService.sendMessage(null, transLog.getPhoneNum(), ShopParameters.TEMPLATE_ID_TAKE_AWAY);
        }
        return transLogMapper.updateTransLog(transLog);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTransLogByIds(String ids) {
        return transLogMapper.deleteTransLogByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteTransLogById(Long id) {
        return transLogMapper.deleteTransLogById(id);
    }


    /**
     * @Author 刘欢
     * @Date 2021/11/10 23:31
     * @Description 获取订单号
     */
    private String getOrderNo() {
        String maxOrderNo = transLogMapper.getMaxOrderNo();
        String orderNo;
        if (StrUtil.isBlankIfStr(maxOrderNo) || maxOrderNo.length() < 16) {
            orderNo = "FBXD" + DateUtil.format(DateUtil.date(), "yyyyMMdd") + "0001";
        } else {
            String serialNo = maxOrderNo.substring(12);
            serialNo = String.valueOf(Integer.parseInt(serialNo) + 1);
            orderNo = "FBXD" + DateUtil.format(DateUtil.date(), "yyyyMMdd") + StrUtil.fill(serialNo, '0', 4, true);
        }
        return orderNo;
    }
}
